package other.two;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileTransfer {


    /**
     * 将源资源地址上传到目标资源地址。相应的鉴权可以忽略，可以使用第三方 HTTP Client 来完成。
     * @param sourceUrl 源资源地址 （例如:腾讯云）
     * @param targetUrl 目标资源地址 （例如:阿里云）
     * @throws RuntimeException
     */
    public static void TransUpload(String sourceUrl, String targetUrl) throws RuntimeException {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            // 打开源资源连接
            URL url = new URL(sourceUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.connect();

            // 检查连接是否成功
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("连接未成功，状态码: " + responseCode);
            }
            FileOutputStream fileOutputStream = new FileOutputStream("G:\\abc\\downloaded_image.jpg");

            // 获取源资源输入流
            inputStream = connection.getInputStream();
            // 打开目标资源连接
            url = new URL(targetUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();

            outputStream = connection.getOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            // 写入数据
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
            System.out.println("文件转存成功.");
        } catch (IOException e) {
            throw new RuntimeException("处理失败.", e);
        } finally {
            // 关闭连接和流
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
            }
        }
    }

    public static void main(String[] args) {
        String sourceUrl = "https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB1lKyvW.img?w=800&h=435&q=60&m=2&f=jpg";
        String targetUrl = "https://example.com/target-file.txt";

        TransUpload(sourceUrl, targetUrl);
    }
}
